USE Lib
GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
----------------------------
IF EXISTS (SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_replace_repetition') BEGIN
	DROP  FUNCTION  tsql.fn_replace_repetition
	PRINT '<<< DROP FUNCTION tsql.fn_replace_repetition - Completed with SUCCESS >>>'
END
GO

/*================================================================================================
Name:			tsql.fn_replace_repetition
Type:			User defined function 
Owner:			
Project:			
Description:	replace repeated char
Parameters:		
Dependens on:  	none
Usage:			SELECT * FROM Lib.tsql.fn_split('1;2;3;4;5',';')
--------------------------------------------------------------------------------------------------
Version:		20070503
SrcCtrlApp:		
SrcCtrlPath:	
--------------------------------------------------------------------------------------------------
History:		05/03/2007 - Adrian E Dudau - Function created
================================================================================================*/
CREATE FUNCTION tsql.fn_replace_repetition
	(  @string NVARCHAR(4000)
	 , @search_for NVARCHAR(4000)
     , @replace_with NVARCHAR(4000)

	 , @min_replace_len INT = 1
	 , @max_replace_len INT = 4000
	)
RETURNS NVARCHAR(4000)
WITH EXECUTE AS CALLER
AS

BEGIN 
	DECLARE @n AS INT

	IF @min_replace_len < 0 
		SET @min_replace_len = 0

	IF @max_replace_len < @min_replace_len 
		SET @max_replace_len = @min_replace_len 

	SET @n = @max_replace_len

	WHILE @n >= @min_replace_len BEGIN 
		SET @string = REPLACE(@string,REPLICATE(@search_for,@n),@replace_with)
		SET @String = REPLACE(@string,REPLICATE(@replace_with,2),@replace_with)
		SET @n = @n - 1
	END

	RETURN @string
END

GO

---------------------------------------------------------------------------
-- BEGIN MAINTENANCE WRAPPER
-- Verify completion
----------------------------
IF EXISTS(SELECT * FROM sysobjects WHERE type = 'FN' AND name = 'fn_replace_repetition') BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_replace_repetition - Completed with SUCCESS >>>'
END
ELSE BEGIN 
	PRINT '<<< CREATE FUNCTION tsql.fn_replace_repetition - Completed with ERROR >>>'
END

GO

----------------------------
-- END MAINTENANCE WRAPPER
---------------------------------------------------------------------------
